﻿using mvcForum.Core;
using mvcForum.Core.Interfaces.Data;
using mvcForum.Web.Controllers;
using mvcForum.Web.Extensions;
using System;
using System.Linq;
using System.Web.Mvc;
using GroupVM = mvcForum.Web.Areas.ForumAPI.ViewModels.Group;

namespace mvcForum.Web.Areas.ForumAPI.Controllers {

	public class GroupController : BaseAPIController {

		[HttpPost]
		[Authorize(Roles = Constants.Roles.SolutionAdmin)]
		public ActionResult Create(GroupVM model, String mode) {
			if (ModelState.IsValid) {
				Group group = new Group(model.Name);

				this.GetRepository<Group>().Create(group);

				this.Context.SaveChanges();

				return new HttpStatusCodeResult(200);
			}
	
			return new HttpStatusCodeResult(500, ModelState.ErrorString());
		}

		[Authorize(Roles = Constants.Roles.Combined)]
		public ActionResult Read(Int32 id, String mode) {
			Group group = this.GetRepository<Group>().Read(id);
			return this.CustomJson(new { Id = group.Id, Name = group.Name });
		}

		[HttpPost]
		[Authorize(Roles = Constants.Roles.SolutionAdmin)]
		public ActionResult Update(GroupVM model, String mode) {
			if (ModelState.IsValid) {
				Group group = this.GetRepository<Group>().Read(model.Id);

				group.Name = model.Name;

				this.Context.SaveChanges();

				return new HttpStatusCodeResult(200);
			}

			return new HttpStatusCodeResult(500, ModelState.ErrorString());
		}

		[HttpPost]
		[Authorize(Roles = Constants.Roles.SolutionAdmin)]
		public ActionResult Delete(Int32  id, String mode) {
			IRepository<Group> groupRepo = this.GetRepository<Group>();
			Group group = groupRepo.Read(id);

			// TODO: Delete user/group relations

			groupRepo.Delete(group);

			this.Context.SaveChanges();

			return new HttpStatusCodeResult(200);
		}

		[Authorize(Roles = Constants.Roles.Combined)]
		public ActionResult List(Int32? page, String mode) {
			return this.CustomJson(new {
				Groups = this.GetRepository<Group>().ReadAll().Select(g => new GroupVM {
					Id = g.Id,
					Name = g.Name,
					ApiUrl = Url.Action("read", "group", new { mode = "json", area = "forumapi", id = g.Id })
				}).OrderBy(g => g.Name)
			});
		}
	}
}